﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using HZU.ZP.Data.Impl;
using HZU.ZP.Data.Interfaces;
using HZU.ZP.Domain.IService;
using HZU.ZP.Domain.Model;
using HZU.ZP.Domain.ServiceImpl.PCSvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HZU.ZP.Controllers
{
    public class AdminController : Controller
    {
        private IAdminService _adminService;
        public AdminController(IAdminService adminService)
        {
            _adminService = adminService;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("AdminLogin", "Admin");
        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult AdminLogin()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public IActionResult AdminLogin(string name, string password)
        {
            var admin = _adminService.Login(name, password);
            if (admin == null)
                return Json(AjaxResult.ReturnMessage(0, "账号或密码错误"));
            else
            {
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Sid, admin.Id.ToString()));
                // identity.AddClaim(new Claim(ClaimTypes.Email, testCompany.Email));
                identity.AddClaim(new Claim(ClaimTypes.Name, admin.Name));
                identity.AddClaim(new Claim(ClaimTypes.Role, admin.Role));
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
                return Json(AjaxResult.ReturnMessage(1, "登录成功"));
            }
        }
       
    }
}
